
use LONG_MI_NATURE_20180111.dta, clear

* DROPPING JAPAN
drop if countryid==20

* GENERATE MEAN ABSOLUTE ERROR
gen mae_ = abs(vote_-poll_)
collapse (mean) mae_ (count) n=mae_, by(daysbeforeED)

drop if mae_ == .
drop if daysbeforeED==0

sort daysbeforeED

* 
twoway /*
*/  || line mae_ daysbeforeED if daysbeforeED<200, /*
*/  clpattern(solid) clcolor(black) clwidth(medthick)  /* 
*/  , scheme(plottig) graphregion(color(white)) /*
*/  xtitle("Days Until Election") /*
*/  title("(a) Mean Absolute Vote-Poll Error over the Election Timeline for All Elections, Raw Polls", size(small)) /*
*/  ylabel(0(1)6, gmax angle(horizontal)) /*
*/  ytick(0(1)6) /*
*/  ytitle(Mean Absolute Error) /*
*/  xlabel(0(50)200) /*
*/  xscale(reverse) xscale(titlegap(2)) /*
*/  saving(Fig1a.gph, replace)

** PRESIDENTIAL VS. PARLIAMENTARY **

* -> LEGISLATIVE ELECTIONS
use LONG_MI_NATURE_20180111.dta, clear
keep if election=="Legislative"
drop if pollcycle<200
drop if daysbeforeED>200
drop if daysbeforeED==0

* DROPPING JAPAN
drop if countryid==20

gen mae_ = abs(vote_-poll_)

collapse (mean) mae_, by(daysbeforeED)

drop if mae_ == .

rename mae_ mae_leg
sort daysbeforeED

save PollErrors_LEG.dta, replace

* -> PRESIDENTIAL ELECTIONS
use LONG_MI_NATURE_20180111.dta, clear
keep if election=="Presidential"
drop if pollcycle<200
drop if daysbeforeED>200
drop if daysbeforeED==0

gen mae_ = abs(vote_-poll_)

collapse (mean) mae_, by(daysbeforeED)

drop if mae_ == .

rename mae_ mae_pres

sort daysbeforeED

merge daysbeforeED using PollErrors_LEG.dta

drop _merge

* 
twoway /*
*/  || line mae_pres daysbeforeED if daysbeforeED<201, /*
*/  clpattern(solid) clcolor(gs8) clwidth(medthick)  /* 
*/  || line mae_leg daysbeforeED if daysbeforeED<201, /*
*/  clpattern(solid) clcolor(gs0) clwidth(medthick)  /* 
*/  , scheme(plottig) graphregion(color(white)) /*
*/  xtitle("Days Until Election") /*
*/  title("(b) Mean Absolute Vote-Poll Error over the Election Timeline for All Elections, Raw Polls, Presidential and Parliamentary Elections", size(small)) /*
*/  ylabel(0(1)10, gmax angle(horizontal)) /*
*/  ytick(0(1)10) /*
*/  ytitle(Mean Absolute Error) /*
*/  xlabel(0(50)200) /*
*/  xscale(reverse) xscale(titlegap(2)) /*
*/  legend(order(1 "Presidential" 2 "Parliamentary") /*
*/  rows(1) /*
*/  symxsize(5) ring(0) position(1) /*
*/  size(small))  /*
*/  saving(Fig1b.gph, replace)

graph combine Fig1a.gph Fig1b.gph, rows(2) graphregion(color(white))

graph export PollError_Fig1.png, width(3000)
graph export PollError_Fig1.eps
